import logging

from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utils.common import get_user_cookie
from info.utils.response_code import RET
from . import blue_print
from info import db,rs


# 连接SQLAlchemy测试
class Man(db.Model):

    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64))

    def __repr__(self):
        return self.name



@blue_print.route('/')
@get_user_cookie
def index():

    user=g.user

    #点击排行处理区域

    #1.获取数据库新闻点击数据排行
    new_click =None
    try:
        new_click = News.query.order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)


    except Exception as e:
        current_app.logger.error(e)

    #分类
    #查询category表
    try:
        category = Category.query.all()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接错误')


    data = {
        'user_id':user.to_dict() if user else None,
        'new_click':new_click,
        'category':category
    }

    return render_template('news/index.html',data=data)


@blue_print.route("/favicon.ico")
def get_web_icon():

    return current_app.send_static_file("news/favicon.ico")


@blue_print.route('/news_list')
def news_list():

    #1.获取参数  请求方式是get,获取参数是以查询字符串形式传递  数据有：page 页数 cid 分类id per_page　每一页要展示的条数
    new_dict = request.args
    per_page=new_dict['per_page']
    cid=new_dict['cid']
    page=new_dict['page']

    #判空,如果有空，则return
    if not all([per_page, cid, page]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    #2.连接数据库查询news数据
    #已知３个参数需要的数据类型是整数类型，进行数据转换
    per_page = int(per_page)
    cid = int(cid)
    page = int(page)

    filter =[]
    if cid !=1:
        filter.append(News.category_id==cid)
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,per_page)
        items = paginate.items   #通过items属性获取５个内容
        cur_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='连接数据库错误')

    #3.已知前端需要newsList的字典对象数据
    newsList =[]
    for new in items:
        print()
        newsList.append(new.to_basic_dict())

    #4.返回数据
    return jsonify(errno=RET.OK, errmsg='连接成功',newsList=newsList,totalPage=total_page,currentPage=cur_page)